package com.gec.system.filter;


import com.alibaba.fastjson.JSON;
import com.gec.system.common.Result;
import com.gec.system.common.ResultCodeEnum;
import com.gec.system.util.JwtHelper;
import com.gec.system.util.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 主要用于判断用户的身份
 */
public class JwtAuthorizationFilter extends OncePerRequestFilter {


    private RedisTemplate redisTemplate;

    public JwtAuthorizationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        logger.info("uri:"+request.getRequestURI());
        //如果是登录接口，直接放行
        if("/system/index/login".equals(request.getRequestURI())||
                        "/system/upload/uploadImage".equals(request.getRequestURI())||
                        "/system/itrUser/checkOutName".equals(request.getRequestURI())||
                        "/system/itrUser/saveOrUpdate".equals(request.getRequestURI())||
                        "/system/itrUser/register".equals(request.getRequestURI())||
                "/system/upload/uploadVideo".equals(request.getRequestURI())
//               || "/system/chat/jdt".equals(request.getRequestURI())
        ) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if(null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        }


        //        //获取请求头的token
//        String tokenHeader = request.getHeader("authorization");
//        System.out.println("header token :" + tokenHeader);
//
//        //判断 token 有效性
//        if (tokenHeader != null && tokenHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
//            UsernamePasswordAuthenticationToken token = getAuthencation(tokenHeader);//验证jwt的方法
//            //重新登记上下文
//            SecurityContextHolder.getContext().setAuthentication(token);
//        }
//        filterChain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        logger.info("token:"+token);
        if (!StringUtils.isEmpty(token)) {
            String useruame = JwtHelper.getUsername(token);
            logger.info("useruame:"+useruame);
            if (!StringUtils.isEmpty(useruame)) {
                String authoritiesString = (String) redisTemplate.opsForValue().get(useruame);
                System.out.println("authoritiesString: "+authoritiesString);
                List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Map map : mapList) {
                    authorities.add(new SimpleGrantedAuthority((String)map.get("authority")));
                }
                return new UsernamePasswordAuthenticationToken(useruame, null, authorities);
                //return new UsernamePasswordAuthenticationToken(useruame, null, Collections.emptyList());
            }
        }
        return null;
    }

//    private UsernamePasswordAuthenticationToken getAuthencation(String tokenHeader) {
//        //去前缀
//        String jwt = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");
//        String username = JwtTokenUtil.getProperties(jwt);
//        if (username != null) {//存在username就视为有效
//            //对比redis（存放账号信息和权限信息）
//            //第三个参数是权限列表（加载redis）
//            return new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
//        }
//
//        return null;
//    }
}
